package cmd

import (
	"fmt"
	"gthoth/internal/app"
	"log"
	"time"

	"github.com/BurntSushi/toml"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/sessions"
)

func Run(fn func()) {
	_, err := toml.DecodeFile("./gthoth.toml", &app.Config)
	if err != nil {
		log.Fatal(err)
	}

	app.App = iris.New().SetName(app.Config.AppName)
	app.App.Use(recover.New())

	// 启用 session
	sess := sessions.New(sessions.Config{Cookie: "gthoth", AllowReclaim: true, Expires: 30 * time.Minute})
	app.App.Use(sess.Handler())

	app.App.HandleDir("/", iris.Dir("./webfe/dist/"))
	app.App.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
		ctx.WriteString("404")
	})

	app.App.Get("/api", func(ctx iris.Context) {
		ctx.JSON(iris.Map{"hello": "world"})
	})

	fn()

	irisConfigure := iris.WithConfiguration(iris.Configuration{
		LogLevel:   "info",
		TimeFormat: "2006-01-02 15:04:05",
		Charset:    "UTF-8",
	})
	app.App.Listen(fmt.Sprintf(":%d", app.Config.AppPort), irisConfigure)
}
